<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>shop cart</title>
		<style>
			.del{
				cursor: pointer;
				color: blue;
			}
		</style>
		<script>
			var ar=[];
			ar.push({name:"cookies",quantity:1,price:46.4});
			ar.push({name:"nike shoes",quantity:12,price:246.3});
			ar.push({name:"apple",quantity:1,price:4.5});
			
			window.onload=function(){
				let c=document.getElementById("shopcart");
			 
				let tq=0,tp=0;
				for(let o of ar){
					let tr=document.createElement("tr");
					tr.innerHTML="<tr><td>"+o.name+"</td><td>"+o.price+"</td><td>"+o.quantity+"</td><td class='del'>删除</td></tr>";
					c.firstElementChild.appendChild(tr);	
					tq+=o.quantity;
					tp+=o.price*o.quantity;
				}
				document.getElementById("tq").innerHTML=tq.toFixed(2);
				document.getElementById("tp").innerHTML=tp.toFixed(2);
			
				//bind delete action
				let dr=document.querySelectorAll(".del");
				dr.forEach(x=>{
					x.onclick=function(){
						let tab=x.parentNode.parentNode;
						tab.removeChild(x.parentNode);
						doCalc();
					} 
				});
				
			}
			//重新计算
			function doCalc(){
				let c=document.getElementById("shopcart");
				let trs=c.firstElementChild.children;
				let tq=0,tp=0;
				for(let i=1;i<trs.length;i++){
					let o=trs[i];
					console.log(o.children[2].innerHTML);
					console.log(o.children[1].innerHTML);
					tq+=parseInt(o.children[2].innerHTML);
					
					tp+=parseInt(o.children[2].innerHTML)*parseFloat(o.children[1].innerHTML);
					
					console.log(tq+","+tp+">>>>>")
					console.log(">>>>>>>>>>>>>>>");
				}
				document.getElementById("tq").innerHTML=tq.toFixed(2);
				document.getElementById("tp").innerHTML=tp.toFixed(2);
			}
		</script>
	</head>
	<body>
		<h3 align="center">shop carts</h3>
		<table id="shopcart" border="1" cellspacing="0" cellpadding="0">
			<tbody id="cart">
				<tr>
					<td>Name</td>
					<td>price</td>
					<td>Quantity</td>
					<td>Action</td>
				</tr> 
			</tbody>
			<tfoot>
				<tr align="right">
					<td id="tq" colspan="2"></td>
					<td id="tp" colspan="2"></td>
				</tr>
			</tfoot>
		</table>
	</body>
</html>